package rms.mall.server.application.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;
import rms.mall.server.api.enums.DeleteEnum;
import rms.mall.server.api.module.system.MenuInfoTO;
import rms.mall.server.api.module.system.MenuMetaTO;
import rms.mall.server.domain.context.CommonContext;
import rms.mall.server.domain.entity.system.MenuInfo;
import rms.mall.server.domain.repository.system.MenuInfoRepository;
import rms.mall.server.domain.utils.BaseConvert;
import rms.mall.server.domain.utils.StreamUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Component
public class MenuInfoService {

    @Resource
    private MenuInfoRepository menuInfoRepository;

    public List<MenuInfoTO> treeMenu() {
        List<MenuInfo> menuInfoList = menuInfoRepository.list();
        List<MenuInfoTO> menuInfos = StreamUtils.convertList(menuInfoList, menuInfo -> {
            MenuInfoTO menuInfoTO = BaseConvert.convert(menuInfo, MenuInfoTO.class);
            menuInfoTO.setMeta(JSON.parseObject(menuInfo.getMeta(), MenuMetaTO.class));
            return menuInfoTO;
        });

        Map<Long, MenuInfoTO> menuInfoMap = StreamUtils.getMap(menuInfos, MenuInfoTO::getId);
        List<MenuInfoTO> resultList = Lists.newArrayList();
        for (MenuInfoTO menuInfo : menuInfos) {
            MenuInfoTO parentMenuInfo = menuInfoMap.get(menuInfo.getParentId());
            if (Objects.isNull(parentMenuInfo)) {
                resultList.add(menuInfo);
                continue;
            }
            List<MenuInfoTO> menuInfoTOS = Optional.ofNullable(parentMenuInfo.getChildren()).orElse(Lists.newArrayList());
            menuInfoTOS.add(menuInfo);
            parentMenuInfo.setChildren(menuInfoTOS);
        }
        return resultList;
    }

    public void createMenu(MenuInfoTO menuInfoTO) {
        MenuInfo menuInfo = BaseConvert.convert(menuInfoTO, MenuInfo.class);
        menuInfo.setMeta(JSON.toJSONString(menuInfoTO.getMeta()));

        menuInfo.setCreated(CommonContext.get().getAcctId());
        menuInfo.setCreateTime(new Date());
        menuInfo.setModifier(CommonContext.get().getAcctId());
        menuInfo.setModifyTime(new Date());
        menuInfo.setDeleted(DeleteEnum.NOT_DELETE.getCode());
        menuInfoRepository.save(menuInfo);
    }

    public void modifyMenu(MenuInfoTO menuInfoTO) {
        MenuInfo menuInfo = BaseConvert.convert(menuInfoTO, MenuInfo.class);
        menuInfo.setMeta(JSON.toJSONString(menuInfoTO.getMeta()));
        menuInfo.setModifier(CommonContext.get().getAcctId());
        menuInfo.setModifyTime(new Date());
        menuInfoRepository.updateById(menuInfo);
    }

    public void deleteMenu(Long id) {
        menuInfoRepository.removeById(id);
    }
}
